package smtp;

import java.io.UnsupportedEncodingException;
import java.util.logging.Logger;

import server.Server;


/* According to 
 * http://www.faqs.org/rfcs/rfc1342.html
 * */
public class SubjectEncoder {
	public static final int CODE_EQUAL = 61;
	public static final int CODE_QUESTIONMARK = 63;
	public static final int CODE_SPACE = 32;
	public static final int CODE_UNDERSCORE = 95;
	public static final String QUOTED_HEADER = "=?ISO-8859-15?Q?";
	public static final String QUOTED_FOOTER = "?=";
	private String line;
	
	public String quoted(int b) {
		return "=" + Integer.toHexString(b).toUpperCase();
	}
	
	
	private void append(String c) {
		this.line += c;
	}
	
	public String encode(String s) {
		
		try {
			byte[] bytes = s.getBytes("ISO-8859-15");
		} catch (UnsupportedEncodingException e) {
			Logger.getLogger(Server.LOG).severe(e.getMessage());
		} //"ISO-8859-15");
		catch (Exception e ) {

		}
		
		
		this.line = SubjectEncoder.QUOTED_HEADER;

		for (int i = 0; i < s.length(); i++) {
			char character = s.charAt(i);	
			char[] tmp = {character};
			String cc = new String(tmp);
			int b = (int) character;
						
			if ((b == CODE_EQUAL) || (b == CODE_QUESTIONMARK)) {				
				this.append(this.quoted(character));
			}
			else if (b == CODE_SPACE) {
				char[] tmp2 = {CODE_UNDERSCORE};
				this.append(new String(tmp2));
			}
			else if ((b >= 9) && (b <= 32)){ // White space
				this.append(cc);
			}
			else if ((b >= 33) && (b <= 126)){ //Symbols
				this.append(cc);
			}	
			else if (b > 126) {
				this.append(this.quoted(character));
			}										
		}
		
		this.line += SubjectEncoder.QUOTED_FOOTER;
		
		return this.line;
	}
	
	/*
	public static void main(String[] args){
		SubjectEncoder encoder = new SubjectEncoder();		
		System.out.println(encoder.encode("Can you encode Swedish characters (öäåÖÄÅ)?"));
	}
	*/	

}
